//
//  SGProgressHUD.m
//  SGProgressHUD
//
//  Created by appbegin on 14-6-23.
//  Copyright (c) 2014年 appbegin. All rights reserved.
//

#import "SGProgressHUD.h"

#define HUD_STATUS_COLOR		[UIColor whiteColor]
#define HUD_SPINNER_COLOR		[UIColor whiteColor]
#define HUD_BACKGROUND_COLOR	[UIColor colorWithWhite:0 alpha:0.8]
#define HUD_STATUS_FONT			[UIFont systemFontOfSize:12]
///[UIFont boldSystemFontOfSize:16]


#define IOS_VERSION_7_AND_ABOVE (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)? (YES):(NO))
#define IOS_VERSION_6 ((([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)&&([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0))? (YES):(NO))

//动画是否完成
BOOL isAnimation;
BOOL isAnother;
NSString *msg;
@implementation SGProgressHUD

+ (SGProgressHUD *)shared
{
	static dispatch_once_t once = 0;
	static SGProgressHUD *progressHUD;
	dispatch_once(&once, ^{ progressHUD = [[SGProgressHUD alloc] init]; });
	return progressHUD;
}

- (id)init
{
	self = [super initWithFrame:[[UIScreen mainScreen] bounds]];
	id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
	if ([delegate respondsToSelector:@selector(window)])
		_window = [delegate performSelector:@selector(window)];
	else _window = [[UIApplication sharedApplication] keyWindow];
	_hud = nil; _spinner = nil; _label = nil;
	self.alpha = 0;
	return self;
}

+ (void)dismiss
{
	[[self shared] hudHide];
}


+ (void)show:(NSString *)status
{
	[[self shared] hudMake:status imgage:nil spin:YES hide:NO];
}

+ (void)showSuccess:(NSString *)status
{
    if (isAnimation) {
        isAnother  = YES;
        msg = status;
    }else{
        [[self shared] hudMake:status imgage:nil spin:NO hide:YES];
    }
}

- (void)hudMake:(NSString *)status imgage:(UIImage *)img spin:(BOOL)spin hide:(BOOL)hide
{
	[self hudCreate];
	_label.text = status;
	_label.hidden = (status == nil) ? YES : NO;
	if (spin) [_spinner startAnimating]; else [_spinner stopAnimating];
    
    [self hudOrient];
    [self hudSize:spin];
	[self hudShow];
	if (hide) [NSThread detachNewThreadSelector:@selector(timedHide) toTarget:self withObject:nil];
}

- (void)hudSize:(BOOL)spin
{
	CGRect labelRect = CGRectZero;
	CGFloat hudWidth = 100, hudHeight = 100;
	if (_label.text != nil)
	{
		NSDictionary *attributes = @{NSFontAttributeName:_label.font};
		NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
        UIFont *font = _label.font;//[UIFont fontWithName:@"Arial" size:15];
        if (IOS_VERSION_7_AND_ABOVE) {
            labelRect = [_label.text boundingRectWithSize:CGSizeMake(200, 300) options:options attributes:attributes context:NULL];
        } else if (IOS_VERSION_6) {
            labelRect.size = [_label.text sizeWithFont:font constrainedToSize:CGSizeMake(200, 300) lineBreakMode:NSLineBreakByCharWrapping];
        }
        if (spin) {
            labelRect.origin.x = 12;
            labelRect.origin.y = 66;
            
            hudWidth = labelRect.size.width + 24;
            hudHeight = labelRect.size.height + 80;
            
            if (hudWidth < 100)
            {
                hudWidth = 100;
                labelRect.origin.x = 0;
                labelRect.size.width = 100;
            }
        } else {
            labelRect.origin.x = 12 - 4;
            labelRect.origin.y = 66 -54;
            
            hudWidth = labelRect.size.width + 24 - 4;
            hudHeight = labelRect.size.height + 80 - 54;
        }
	}
    
	CGSize screen = [UIScreen mainScreen].bounds.size;
    
	_hud.center = CGPointMake(screen.width/2, screen.height/2);
	_hud.bounds = CGRectMake(0, 0, hudWidth, hudHeight);
    
	CGFloat imagex = hudWidth/2;
	CGFloat imagey = (_label.text == nil) ? hudHeight/2 : 36;
    _spinner.center = CGPointMake(imagex, imagey);
    
	_label.frame = labelRect;
}

- (void)hudShow
{
	if (self.alpha == 0)
	{
		self.alpha = 1;
        
		_hud.alpha = 0;
		_hud.transform = CGAffineTransformScale(_hud.transform, 1.4, 1.4);
        
		NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut;
        
		[UIView animateWithDuration:0.3 delay:0 options:options animations:^{
			_hud.transform = CGAffineTransformScale(_hud.transform, 1/1.4, 1/1.4);
			_hud.alpha = 1;
		}
                         completion:^(BOOL finished){ }];
	}
}

- (void)hudCreate
{
    
    if (_backView == nil) {
        _backView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//        _backView.backgroundColor = [UIColor purpleColor];
        [_window addSubview:_backView];
    }
    
	if (_hud == nil)
	{
		_hud = [[UIToolbar alloc] initWithFrame:CGRectZero];
        if (IOS_VERSION_7_AND_ABOVE) {
            _hud.barTintColor = HUD_BACKGROUND_COLOR;
        } else if (IOS_VERSION_6) {
            _hud.tintColor = HUD_BACKGROUND_COLOR;
        }
		_hud.translucent = YES;
		_hud.layer.cornerRadius = 10;
		_hud.layer.masksToBounds = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rotate:) name:UIDeviceOrientationDidChangeNotification object:nil];
	}
	if (_hud.superview == nil) [_backView addSubview:_hud];
	if (_spinner == nil)
	{
		_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		_spinner.color = HUD_SPINNER_COLOR;
		_spinner.hidesWhenStopped = YES;
	}
	if (_spinner.superview == nil) [_hud addSubview:_spinner];
    
	if (_label == nil)
	{
		_label = [[UILabel alloc] initWithFrame:CGRectZero];
		_label.font = HUD_STATUS_FONT;
		_label.textColor = HUD_STATUS_COLOR;
		_label.backgroundColor = [UIColor clearColor];
		_label.textAlignment = NSTextAlignmentCenter;
		_label.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
		_label.numberOfLines = 0;
	}
	if (_label.superview == nil) [_hud addSubview:_label];
}

- (void)hudHide
{
	if (self.alpha == 1)
	{
		NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseIn;
        isAnimation = YES;
		[UIView animateWithDuration:0.5 delay:0 options:options animations:^{
			_hud.transform = CGAffineTransformScale(_hud.transform, 0.7, 0.7);
			_hud.alpha = 0;
		}
                         completion:^(BOOL finished)
         {
             isAnimation = NO;
             [self hudDestroy];
             self.alpha = 0;
             
             if (isAnother) {
                 isAnother = NO;
                 [[self class] showSuccess:msg];
             }
         }];
	}
}

- (void)hudDestroy
{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
	[_label removeFromSuperview];	_label = nil;
    
	[_spinner removeFromSuperview];	_spinner = nil;
	[_hud removeFromSuperview];		_hud = nil;
    [_backView removeFromSuperview];	_backView = nil;
}

- (void)timedHide
{
	@autoreleasepool
	{
		double length = _label.text.length;
		NSTimeInterval sleep = length * 0.04 + 0.5;
		
		[NSThread sleepForTimeInterval:sleep];
		[self hudHide];
	}
}

- (void)hudOrient
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
	CGFloat rotate = 0.0;
	//---------------------------------------------------------------------------------------------------------------------------------------------
	UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
	//---------------------------------------------------------------------------------------------------------------------------------------------
	if (orient == UIInterfaceOrientationPortrait)			rotate = 0.0;
	if (orient == UIInterfaceOrientationPortraitUpsideDown)	rotate = M_PI;
	if (orient == UIInterfaceOrientationLandscapeLeft)		rotate = - M_PI_2;
	if (orient == UIInterfaceOrientationLandscapeRight)		rotate = + M_PI_2;
	//---------------------------------------------------------------------------------------------------------------------------------------------
	_hud.transform = CGAffineTransformMakeRotation(rotate);
}

- (void)rotate:(NSNotification *)notification
{
	[self hudOrient];
}

@end
